import os
from datetime import datetime

from combinations.conf import logger

import pandas as pd

from .config import COMBO_NAME_PREFIX

current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class MarkdownGenerator:
    def __init__(self, file_dir):
        now = datetime.now()
        current_time = f"{now.year}年{now.month}月{now.day}日-{now.hour}时{now.minute}分{now.second}秒"

        excel_file = f"combinations_{current_time}.xlsx"
        combination_dir = os.path.join(current_dir, "record", file_dir)
        if not os.path.exists(combination_dir):
            os.makedirs(combination_dir)
        # else:
        #     import shutil
        #     shutil.rmtree(combination_dir)  # 删除目录及其内容
        #     os.makedirs(combination_dir)  # 重新创建目录
        self.excel_file = os.path.join(current_dir, "record", file_dir, excel_file)

    #
    # def generate_table(self, combinations: list):
    #     """生成Markdown表格"""
    #     try:
    #
    #         logger.info("开始生成Markdown表格")
    #         with open(self.output_file, "w", encoding="utf-8") as md_file:
    #             for i, combo in enumerate(combinations):
    #                 logger.info(f"正在写入第{i + 1}行:{combo}")
    #                 if i == 0:
    #                     title = '| 组合名称 |'
    #                     line = '|---------|'
    #                     # logger.info("写入Markdown表格头部")
    #                     for j in combo:
    #                         # 将路径的目录部分转换为字符串并拼接到 title
    #                         if '/' in j:
    #                             title = title + '\\'.join(j.split('/')[:-1]) + '|'
    #                         else:
    #                             title = title + '\\'.join(j.split('\\')[:-1]) + '|'
    #                         line = line + '-----|'
    #
    #                     md_file.write(f"{title}\n")
    #                     md_file.write(f"{line}\n")
    #                 combo_name = f"{COMBO_NAME_PREFIX}{i}"
    #                 row = [combo_name] + list(combo)
    #                 md_file.write(f"| {' | '.join(row)} |\n")
    #         # logger.info(f"Markdown文件 {self.output_file} 生成成功")
    #     except Exception as e:
    #         logger.error(f"生成Markdown表格失败: {str(e)}")

    def generate_excel(self, combinations: list, ):
        """生成Excel文件"""
        try:
            logger.info("开始生成Excel文件")
            # 准备数据
            data = []
            # print(combinations)
            logger.info(f"正在生成Excel文件{combinations}")
            for i, combo in enumerate(combinations, start=0):
                if i == 0:
                    headers = ["组合名称"]
                    for j in combo:
                        # 第一行作为表头
                        if '/' in j:
                            headers = headers + ['\\'.join(j.split('/')[:-1])]
                        else:
                            headers = headers + ['\\'.join(j.split('\\')[:-1])]
                    data.append(headers)
                combo_name = f"{COMBO_NAME_PREFIX}{i}"
                row = [combo_name] + list(combo)
                data.append(row)

            # 创建DataFrame
            df = pd.DataFrame(data[1:], columns=data[0])

            # 写入Excel文件
            df.to_excel(self.excel_file, index=False)
            logger.info(f"Excel文件 {self.excel_file} 生成成功")
        except Exception as e:
            logger.error(f"生成Excel文件失败: {str(e)}")
